﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Agile.Engine.Utils
{
    /// <summary>
    /// 字符工具
    /// </summary>
    public class StringUtils
    {
        /// <summary>
        /// 转换字符到md5
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string ToMD5(string source)
        {
            var md5 = System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(source));
            return BitConverter.ToString(md5).Replace("-", string.Empty);
        }
                
        /// <summary>
        /// 是否为空
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsEmpty(object str)
        {
            return (str == null || str == DBNull.Value || string.IsNullOrEmpty(str.ToString()));
        }

        public static string NullString(object str)
        {
            return IsEmpty(str) ? string.Empty : str.ToString();
        }

        /// <summary>
        /// 转换对象到json字符串
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string ToJson(object json)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(json);
        }

        /// <summary>
        /// 转换json字符串到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T FromJson<T>(string json)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 先转JSON再转Base64
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJsonBase64(object obj)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(ToJson(obj)));
        }

        /// <summary>
        /// 先解Base64再解JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="s"></param>
        /// <returns></returns>
        public static T FromJsonBase64<T>(string s)
        {
            return FromJson<T>(Encoding.UTF8.GetString(Convert.FromBase64String(s)));
        }


    }
}
